import store from "@/store";
import tips from "@/utils/tips";
import Request, {HttpResponse} from "luch-request";
import appConfig from "../config/config";

const http = new Request()
/* 设置全局配置 */
http.setConfig((config: any) => {
    config.header = config.header || {}
    config.baseURL = appConfig.lianke_api
    return config
})

//请求前拦截，用来动态加参,例如token
http.interceptors.request.use((config: any) => { // 可使用async await 做异步操作
    config.header = {...config.header, ApiKey: store.state.settings.lianke_token, Accept: "application/json"}
    if (config.custom.loading) {
        store.commit("loading", true);
    }
    /**
     /* 演示
     if (!token) { // 如果token不存在，return Promise.reject(config) 会取消本次请求
     return Promise.reject(config)
     }
     **/
    return config
}, config => { // 可使用async await 做异步操作
    return Promise.reject(config)
})

// 请求后
http.interceptors.response.use(
    (response) => {
        const data = response.data;
        const custom = response.config?.custom;
        const {statusCode} = response;
        console.log(data)
        if (custom?.loading == true) {
            store.commit("loading", false);
        }
        if (data.code !== 200) {
            // 如果没有显式定义custom的toast参数为false的话，默认对报错进行toast弹出提示
            if (custom?.toast != false) {
                tips.toast(data.msg);
            }
            // 如果需要catch返回，则进行reject
            if (custom?.catch) {
                return Promise.reject(data);
            } else {
                // 否则返回一个pending中的promise，请求不会进入catch中
                return new Promise(() => {
                });
            }
        }
        // return data.data === undefined ? data : data.data;
        return data.data === undefined ? {} : data;
    },
    (response) => {
        const custom = response.config?.custom;

        if (custom?.loading == true) {
            store.commit("loading", false);
        }
        const {statusCode, data} = response;
        // 对响应错误做点什么 （statusCode !== 200）
        console.log('statusCode', statusCode);

        if (statusCode == 401) {
            // tips.toast("请登录");
            store.commit("logout");
        } else if (statusCode == 422) {
            //内容犯规
            store.commit("foulContentModalVisible", data.message);
        } else {
            if (custom?.toast != false) {
                tips.toast('失败');
            }
        }
        return Promise.reject(response);
    }
);
export default http;
